<template>
    <div class="directory-tree app-left app-left-width bg-white" v-loading="loading">
        <!-- <div class="head-container-tit">
            <span class="map-icon"></span> 全局地图目录
        </div> -->
        <div class="head-container">
            <el-input
                v-model="dirName"
                placeholder="数据库名、表名进行查询"
                clearable
                size="small"
                suffix-icon="el-icon-search"
                @input="handleDirName"
                style="margin-bottom: 20px"
            >
            <!-- <el-select v-model="searchType" slot="prepend" @change="selectHandleLibrary" placeholder="请选择" class="input-with-select">
                <el-option label="按库名" value="library"></el-option>
                <el-option label="按表名" value="tableNme"></el-option>
            </el-select> -->
            </el-input>
        </div>
        <div class="mytree directory-tree-node">
            <div class="directory-tree-box">
                <el-tree
                    v-show="searchType == 'library' || searchType == '按库名'"
                    :data="databaseTree"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode"
                    :highlight-current='true'
                    :indent='0'
                    :current-node-key="currentNodeKey"
                    default-expand-all
                    draggable
                    ref="tree"
                    node-key="id"
                    @node-click="handleNodeClick"
                >
                    <span class="el-tree-node__label custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                        <span class="clipboard" v-if="data.isTable">
                            <el-button
                                type="text"
                                size="mini"
                                icon="el-icon-document-copy"
                                v-clipboard:copy="handleCopyNode(node)"
                                v-clipboard:success="onCopySuccess"
                                v-clipboard:error="onCopyError"
                            >
                            </el-button>
                        </span>
                    </span>
                </el-tree>
            </div>
            <div v-show="searchType == 'tableNme'">
                <div v-show="!tableList.length" class="not-data">暂无数据</div>
                <div class="table-item" v-for="(item,index) in tableList" :key="index"  @click="handlebtableNodeClick(item)">
                    <div :class="['table-item-top',item.tableName.length>30?'narrowSize':'']">{{item.tableName}}</div>
                    <div class="table-item-bottom">{{item.tableAlias}}</div>
                </div>
            </div>
        </div>
      </div> 
</template>

<script>
import { mapTreeItem } from "@/api/dataManagement/system/dir";
import { getDatabeseList, searchTableList } from "@/api/dataManagement/system/info";
import Clipboard from 'clipboard';

export default {
    name: 'ApplicationDirectoryTree',
    data() {
        return {
            loading: false,
            // 部门树选项
            databaseTree: undefined,
            // 数据库表名称
            dirName: undefined,
            // 表单参数
            form: {},
            defaultProps: {
                children: "children",
                label: "dirName"
            },
            currentNodeKey: undefined,
            searchType: '按库名',
            tableList:[]
        }
    },
    watch: {
        // 根据名称筛选部门树
        dirName(val) {
            if(this.searchType == '按库名' || this.searchType == 'library') {
                if(!val) return this.getDatabaseTree();
                this.$refs.tree.filter(val.toUpperCase());
            }
        },
        currentNodeKey(id) {
            // Tree 内部使用了 Node 类型的对象来包装用户传入的数据，用来保存目前节点的状态。可以用 $refs 获取 Tree 实例
            var that =  this;
            if (id.toString()) {
                var that = this;
                that.$nextTick(()=>{
                    that.$refs.tree.setCurrentKey(Number(id));
                })
            } else {
                that.$nextTick(()=>{
                    that.$refs.tree.setCurrentKey(Number(id));
                })
            }
        }
    },
    created() {
        this.getDatabaseTree()
        // this.currentNodeKey = Number(this.$route.query.dirId)
    },
    methods: {
        // 根据目录ID获取所有表
        getDbTableList(dirId, data) {
            if (this.loading) return
            this.loading = true
            getDatabeseList({ dirId, pageSize: 65535, filter: true }).then(res => {
                let tree = []
                for (let i = 0; i < res.rows.length; i++) {
                    const item = res.rows[i];
                    if (!item.accessType) continue;
                    let tmp = {
                        id: item.id,
                        dirName: `${item.tableName} (${item.sourceName})`,
                        parentId: dirId,
                        datasourceId: null,
                        isTable: true,
                        accessType: null,
                        sort: null,
                        prefix: null,
                        _tableName: item.tableName,
                        _sourceName: item.sourceName,
                        children: []
                    }
                    tree.push(tmp)
                }

                if (tree.length) {
                    data.children = tree
                } else {
                    this.$message.warning(`${data.dirName} 目录没有更多节点数据`)
                }
                this.loading = false
			}).catch(() => {
                this.loading = false
            })
        },
        // 获取数据库表单目录
        getDatabaseTree() {
            if (this.loading) return
            this.loading = true
            mapTreeItem({ filter: true }).then(res => {
                if ( res.code == 200 ) {
                    this.databaseTree = res.data.children
                    // this.queryParams.dirId =  this.$route.query.dirId || this.databaseTree[0].children[0].id
                    // sessionStorage.setItem("dirId",JSON.stringify(this.databaseTree[0].children[0].id))
                    // this.getList();
                }
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },
        // 监听地图搜索框
        handleDirName(){
            if (this.searchType =='tableNme') {
                if(!this.dirName) {
                    this.tableList =[]
                }
                if (this.dirName.length > 2) {
                    searchTableList({tableName:this.dirName}).then(res=>{
                        let data = res.data;
                        for(let i=0;i<data.length;i++){
                            data[i].children = []
                            data[i].tableNameAndabAlias = data[i].tableName + ' | ' +data[i].tableAlias
                        }
                        this.tableList = data
                    })
                }
            }
        },
        // 监听地图下拉框
        selectHandleLibrary(){
            this.dirName =''
            if(this.searchType =='tableNme') {
                this.tableList = [];
            } else {
                this.getDatabaseTree();
                this.defaultProps.label = 'dirName';
            }
        },
        // 筛选节点
        filterNode(value, data,node) {
            console.log(value, data)
            if (!value) return true;
            let _array = []; //这里使用数组存储 只是为了存储值。.
            
            this.getReturnNode(node, _array, value);
            let result = false;
            _array.forEach(item => {
                result = result || item;
            });
            return result;
        },
        getReturnNode(node, _array, value){
            let isPass =
                node.data &&
                node.data.dirName &&
                node.data.dirName.indexOf(value) !== -1;

            isPass ? _array.push(isPass) : "";

            if (!isPass && node.level != 1 && node.parent) {
                this.getReturnNode(node.parent, _array, value);
            }
        },
        // 节点单击事件
        handleNodeClick(data) {
            if(this.searchType == 'library' || this.searchType == '按库名') {
                // if(this.$route.query.dirId == data.id) return;
                // this.queryParams.dirId = data.id;
                // this.queryParams = Object.assign(this.queryParams,{ tableName: undefined,fieldName: undefined,accessType: undefined,})
                // this.$router.push("/DMS/dataMap/mapDirectory?dirId="+data.id);
                // this.getList();
                // this.getTableMapList()
            }

            // 根据目录ID获取数据表，触发条件：最后一级 && 非数据表
            if (data.id && !data.isTable && !data.children.length) {
                this.getDbTableList(data.id, data)
            } else {
                // TODO 复制表名
            }
        },
        handlebtableNodeClick(data){
            console.log(data)
            // this.$router.push("/DMS/dataMap/mapDirectory/details/"+data.id+'?dirId='+data.dirId);
        },
        handleCopyNode(node) {
            return `${node.data._sourceName}.${node.data._tableName}`
        },
        onCopySuccess() {
            this.msgSuccess('复制成功')
        },
        onCopyError() {
            this.msgError('复制失败！')
        }
   }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/system/tree.scss";

/* 
 * Element class start
 */
.head-container ::v-deep{
   .el-select .el-input {
    width: 100px;
  }
   .el-input__inner{
      padding-right:44px;
   }
   .el-input__suffix-inner{
      display: inline-block;
      .el-icon-search{
         display: inline-block;
         width:44px;
         font-size:16px;
      }
   }
   >.el-input__suffix::before{
      content: '';
      display: inline-block;
      border-left:1px solid #ddd;
      height:20px;
      position: absolute;
      top:50%;
      margin-top:-10px;
      left:0;
   }
   .el-input-group__prepend {
      background-color: #fff;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      .el-input__inner{
         height: 32px;
         line-height: 31px;
      }
   }
}
.el-row {
   margin-right: 0px !important;
   margin-left: 0px !important;
}
.el-checkbox__input.is-checked + .el-checkbox__label {
   padding-right: 6px !important;
}
/* 
 * Element class end
 */

.directory-tree::v-deep {
    .el-tree-node__label {
        padding-left: 5px;
    }
}

.app-container::v-deep{
   /* padding:0;
   background: #F4F4F4; */
   .el-checkbox__label, .el-button--mini, .el-form-item__label{
      font-size:14px;
   }
}

.head-container-tit {
   display: flex;
   align-items: center;
   font-size: 18px;
   padding:5px 0 20px 0;
   .map-icon {
      width: 4px;
      height: 21px;
      display: inline-block;
      background: #1183f8;
      margin-right: 8px;
   }
}

.table-item{
   border-bottom:1px solid #ddd;
    color:#606266;
   &:hover{
      cursor: pointer;
      background-color: #F5F7FA;
   }
   .table-item-top{
      font-size: 16px;
      font-weight: bold;
      padding-left:10px;
      margin-top:10px;
   }
   .narrowSize{
      font-size:14px;
   }
   .table-item-bottom{
      padding:10px 0;
      font-size: 12px;
      padding-left:10px;
   }
}

.not-data{
   font-size:14px;
   color:#909399;
   text-align: center;
   line-height:60px;
}

.directory-tree {
    &.app-left {
        &-width{
            width: 550px;
        }
    }
}
.directory-tree-node{
   height: 400px;
   overflow: auto;
}
.directory-tree-box {
    min-width: 100%;
    // height: 100%;
    padding-right: 10px;
    display: -webkit-inline-box;
    overflow:auto;

    .el-tree {
        width: 100%;
    }

    .custom-tree-node {
        .clipboard {
            margin-left: 8px;
        }
    }
}
</style>